package com.wedo.book.controller;

import com.wedo.book.mapper.CategoryMapper;
import com.wedo.book.pojo.Category;
import com.wedo.book.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @GetMapping("list")
    public ResponseEntity<List<Category>> queryCategories() {
        List<Category> result = this.categoryService.queryCategories();
        if (CollectionUtils.isEmpty(result)) {
            return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
        }
        return ResponseEntity.ok(result);
    }

    @PostMapping
    public ResponseEntity<Category> addCategory(@RequestBody Category category) {
        this.categoryService.addCategory(category);
        return ResponseEntity.ok(category);
    }

    @DeleteMapping
    public ResponseEntity<Category> deleteCategory(@RequestBody Category category) {
        this.categoryService.deleteCategory(category.getId());
        return ResponseEntity.ok(category);
    }

    @PutMapping
    public ResponseEntity<Category> updateCategory(@RequestBody Category category) {
        this.categoryService.updateCategory(category);
        return ResponseEntity.ok(category);
    }

    @GetMapping("bid/{bid}")
    public ResponseEntity<List<Category>> queryCategoryByBid(@PathVariable("bid") Long bid) {
        List<Category> result = this.categoryService.queryCategoryByBid(bid);
        if (CollectionUtils.isEmpty(result)) {
            return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
        }
        return ResponseEntity.ok(result);
    }

    @GetMapping("cid/{cid}")
    public ResponseEntity<Category> queryCategoryById(@PathVariable("cid")Long cid) {
        Category result = this.categoryService.queryCategoryById(cid);
        if (result == null) {
            return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
        }
        return ResponseEntity.ok(result);
    }

}
